//
//  IdeaDetallViewController.m
//  LiangYa_BObject
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 YuHao. All rights reserved.
//

#import "IdeaDetallViewController.h"
#import "IdeaDetallTableViewCell.h"
#import "IdeaDetallHeadTableViewCell.h"
#import "IdeaDetailData.h"
#import "WebViewController.h"
#import "IdeaCol.h"
#import "CollectHandler.h"
#import "IdeaDataWebViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDKUI.h>

@interface IdeaDetallViewController ()<UITableViewDataSource,UITableViewDelegate>{
    MBProgressHUD *HUD;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *IdeaDetallArr;
@property (nonatomic, strong) NSString *itemUrl; // webView地址
@property (nonatomic, strong) UIBarButtonItem *cameraItem;
@property (nonatomic, strong) UIView *menuV;
@property (nonatomic, strong) UIImageView *menuCornerIV;
@property (nonatomic, strong) UIButton *menuBtn;
@property (nonatomic, strong) UIButton *button2;
@property (nonatomic, strong) UIButton *backB;

@end

@implementation IdeaDetallViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tableView.userInteractionEnabled = YES;
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = self.ideaData.albumName;
    self.view.backgroundColor = [UIColor cyanColor];
    self.IdeaDetallArr = [NSMutableArray array];
    [self handleData];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = NO;
    self.tableView.backgroundColor = [UIColor clearColor];
    _tableView.bounces = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    UIImageView *backImageView = [[UIImageView alloc] init];
    [backImageView sd_setImageWithURL:[NSURL URLWithString:self.ideaData.pic]];
    self.tableView.backgroundView = backImageView;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[IdeaDetallHeadTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.tableView registerClass:[IdeaDetallTableViewCell class] forCellReuseIdentifier:@"ideaCell"];
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"数据加载中...";
    
    self.menuV = [[UIView alloc] init];
    self.menuV.frame = CGRectMake(ScreenWidth - 120, 18 + 64, 110, 60);
    self.menuV.layer.cornerRadius = 10;
    self.menuV.backgroundColor = [UIColor whiteColor];
    
    self.menuCornerIV = [[UIImageView alloc] init];
    self.menuCornerIV.image = [[UIImage imageNamed:@"picture2"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    self.menuCornerIV.frame = CGRectMake(ScreenWidth - 45, 64, 20, 20);
    self.menuV.hidden = YES;
    self.menuCornerIV.hidden = YES;
    
    
    UIImage *imageM = [[UIImage imageNamed:@"picture.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.menuBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [_menuBtn setImage:imageM forState:UIControlStateNormal];
    _menuBtn.frame = CGRectMake(0, 0, 20, 20);
    [_menuBtn addTarget:self action:@selector(menuAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_menuBtn];
    _menuBtn.hidden = NO;
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeSystem];
    button1.frame = CGRectMake(10, 0, 90, self.menuV.bounds.size.height / 2-1);
    [button1 setTitleColor:[UIColor blackColor] forState:normal];
    [self.menuV addSubview:button1];
    [button1 setTitle:@"分享" forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(button1Action:) forControlEvents:UIControlEventTouchUpInside];

    self.button2 = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button2.frame = CGRectMake(10, self.menuV.bounds.size.height / 2 , 90, self.menuV.bounds.size.height/ 2 - 1);
    [self.menuV addSubview:self.button2];
    [self.button2 setTitleColor:[UIColor blackColor] forState:normal];
    
    [self.button2 addTarget:self action:@selector(button12Action:) forControlEvents:UIControlEventTouchUpInside];

    [self.view addSubview:self.menuV];
    [self.view addSubview:self.menuCornerIV];
    
    // 返回按钮
    self.backB = [UIButton buttonWithType:UIButtonTypeSystem];
    _backB.backgroundColor = [UIColor colorWithRed:1.000 green:0.000 blue:0.139 alpha:1.000];
    _backB.frame = CGRectMake(20, Screenheight - 60, 40, 40);
    _backB.layer.cornerRadius = 20;
    UIImage *backI = [[UIImage imageNamed:@"picture1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [_backB setImage:backI forState:UIControlStateNormal];
    [_backB setImageEdgeInsets:UIEdgeInsetsMake(5, 5, 5, 5)];
    if (self.boo == NO) {
        _backB.hidden = NO;
    }else{
        _backB.hidden = YES;
    }
    
    [_backB addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_backB];
    
}
#pragma mark 分享
- (void)button1Action:(UIButton *)btn
{
    self.menuV.hidden = YES;

    self.menuV.hidden = YES;
    NSString *urlString = self.ideaData.pic;
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:urlString];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:[NSString stringWithFormat:@"分享:<%@>",self.ideaData.albumName]
                                     images:@[image]
                                        url:[NSURL URLWithString:self.ideaData.pic]
                                      title:@"分享标题"
                                       type:SSDKContentTypeImage];
    [ShareSDK showShareActionSheet:nil
                             items:nil
                       shareParams:shareParams
               onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
                   switch (state) {
                       case SSDKResponseStateSuccess:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateFail:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                               message:[NSString stringWithFormat:@"%@", error]
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       case SSDKResponseStateCancel:
                       {
                           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享已取消"
                                                                               message:nil
                                                                              delegate:nil
                                                                     cancelButtonTitle:@"确定"
                                                                     otherButtonTitles:nil];
                           [alertView show];
                           break;
                       }
                       default:
                           break;
                   }
                   
                   
               }];
    
}

- (void)backAction:(UIButton *)btn
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)menuAction:(UIButton *)btn
{
    CollectHandler *collectHandler = [CollectHandler instandDefault];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"IdeaCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"albumName contains '%@'",self.ideaData.albumName]];
    NSArray *arr = [collectHandler.managedObjectContext executeFetchRequest:request error:nil];
    if (arr.count == 0) {
        [self.button2 setTitle:@"收藏" forState:UIControlStateNormal];

    } else {
        [self.button2 setTitle:@"取消收藏" forState:UIControlStateNormal];

    }
    
    if (self.menuV.hidden) {
        self.menuV.hidden = NO;
        self.menuCornerIV.hidden = NO;
    }else{
        self.menuV.hidden = YES;
        self.menuCornerIV.hidden = YES;
    }
    
}

#pragma mark 收藏方法
- (void)button12Action:(UIBarButtonItem *)btn
{
    CollectHandler *collectHandler = [CollectHandler instandDefault];
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"IdeaCol"];
    request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"albumName contains '%@'",self.ideaData.albumName]];
    NSArray *arr = [collectHandler.managedObjectContext executeFetchRequest:request error:nil];
    
    if (arr.count == 0) {
        [self.button2 setTitle:@"取消收藏" forState:UIControlStateNormal];
        IdeaCol *ideaCol = [NSEntityDescription insertNewObjectForEntityForName:@"IdeaCol" inManagedObjectContext:collectHandler.managedObjectContext];
        ideaCol.albumName = self.ideaData.albumName;
        ideaCol.pic = self.ideaData.pic;
        ideaCol.attribute = self.ideaData.albumLink;
        ideaCol.detail = self.ideaData.detail;
        [collectHandler saveContext];
        NSLog(@"123");
        self.menuV.hidden = YES;
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
    } else {
        [self.button2 setTitle:@"收藏" forState:UIControlStateNormal];
        self.menuV.hidden = YES;
        IdeaCol *ideaFetch = [arr lastObject];
        [collectHandler.managedObjectContext deleteObject:ideaFetch];
        [collectHandler saveContext];

        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"取消收藏成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.IdeaDetallArr.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        IdeaDetallHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor clearColor];
        cell.albumNameLabel.text = self.ideaData.albumName;
        cell.detailLabel.text = self.ideaData.detail;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        IdeaDetallTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ideaCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        IdeaDetailData *ideaDetallData = [self.IdeaDetallArr objectAtIndex:indexPath.row - 1];
        [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:ideaDetallData.pic] placeholderImage:[UIImage imageNamed:@"baikejiaju.png"]];
        cell.detailLabel.text = ideaDetallData.detail;
        if (ideaDetallData.price != nil) {
            NSString *str = [@"￥" stringByAppendingFormat:@"%@",ideaDetallData.price ];
        cell.priceLabel.text = str;
        } else {
            cell.priceLabel.hidden = YES;
        }
        cell.backgroundColor = [UIColor clearColor];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return Screenheight / 4;
    }else {
        IdeaDetailData *ideaDetall = [self.IdeaDetallArr objectAtIndex:indexPath.row - 1];
        CGRect rect = [ideaDetall.detail boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width,100000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17]} context:nil];
        return (rect.size.height + 280) > 290 ? (rect.size.height + 280) : 290;
    }
}

#pragma mark 网络请求数据加载
- (void)handleData
{
    NSString *str = self.ideaData.albumLink;
    
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/json",@"application/json",@"text/javascript",@"text/html", nil];
    [manager GET:str parameters:nil success:^(NSURLSessionDataTask * task, id responseObject) {
        if (responseObject != nil) {
            [HUD removeFromSuperview];
            NSDictionary *dic = [responseObject objectForKey:@"data"];
            NSArray *arr = [dic objectForKey:@"data"];
            for (NSDictionary *dic1 in arr) {
                IdeaDetailData *ideaDetallData = [[IdeaDetailData alloc] init];
                [ideaDetallData setValuesForKeysWithDictionary:dic1];
                [self.IdeaDetallArr addObject:ideaDetallData];
            }
            [self.tableView reloadData];
    } else {
        [HUD removeFromSuperview];

        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"返回" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"服务器数据错误" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:alertAction];
        
        [self presentViewController:alertVC animated:YES completion:^{
            
        }];
        
    }
    }failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
         
     }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        
    }else {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
//        tableView.userInteractionEnabled = NO;
        IdeaDetailData *ideaDetalldata = [self.IdeaDetallArr objectAtIndex:indexPath.row - 1];
        
        NSString *str = [@"http://hws.m.taobao.com/cache/wdetail/5.0/?id=" stringByAppendingFormat:@"%@%@",ideaDetalldata.itemId,@"&ttid=2013@taobao_h5_1.0.0&exParams="];
//        if (self.boo == 1) {
//            IdeaDataWebViewController *webVC = [[IdeaDataWebViewController alloc] init];
//            webVC.webUrl = str;
//            [self.navigationController pushViewController:webVC animated:YES];
//        } else {
//            
//        }
        IdeaDataWebViewController *webVC = [[IdeaDataWebViewController alloc] init];
        webVC.webUrl = str;
        [self presentViewController:webVC animated:YES completion:^{
            
        }];
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
